using Beauty.Net.Cache.Core;
using Beauty.NetWebApi.RequestDto;
using Microsoft.AspNetCore.Mvc;

namespace Beauty.NetWebApi.Controllers
{
    /// <summary>
    /// 天气预测控制器
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly ICacheService _cacheService;
        private const string WeatherCacheKey = "weather:forecast";

        public WeatherForecastController(ILogger<WeatherForecastController> logger, ICacheService cacheService)
        {
            _logger = logger;
            _cacheService = cacheService;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public async Task<IEnumerable<WeatherForecast>> Get()
        {
            // 使用缓存获取天气数据，缓存10分钟
            var forecasts = await _cacheService.GetOrSetAsync(
                key: WeatherCacheKey,
                factory: async () =>
                {
                    _logger.LogInformation("缓存未命中，生成新的天气数据");
                    // 模拟异步操作
                    await Task.Delay(100);
                    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                    {
                        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                        TemperatureC = Random.Shared.Next(-20, 55),
                        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
                    })
                    .ToArray();
                },
                expiry: TimeSpan.FromMinutes(10));

            return forecasts;
        }

        [HttpPost("clear-cache")]
        public async Task<IActionResult> ClearCache()
        {
            await _cacheService.RemoveAsync(WeatherCacheKey);
            _logger.LogInformation("天气数据缓存已清除");
            return Ok(new { message = "缓存已清除" });
        }

        [HttpPost("GetString")]
        public async Task<IActionResult> GetString(WeatherForecastInput input)
        {
            throw new Exception("测试全局异常处理中间件");
            return Ok(new { message = input.Body });
        }
    }
}
